﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceBus.EndPoint;
using ServiceBus.Contract;

namespace ServiceBus.EBSEngine
{
    public static class BusEngine
    {
        static BusEngine()
        {
        }
        public static event EventHandler<Message> MessageDelivered;
        public static event EventHandler Disconnected;
        public static event EventHandler HeartBeatMessage;
        private static List<SAOServiceStructre<ISAOService>> ServiceList = new List<SAOServiceStructre<ISAOService>>();
        public static void RegisterNewService(string name,string address)
        {
            SAOServiceStructre<ISAOService> service =
                new SAOServiceStructre<ISAOService>(name, address);
            service.MessageService.MessageDelivered += new EventHandler<Message>(messageDelivered);
            service.MessageService.ServerDisconnectedEvent += new EventHandler(MessageService_ServerDisconnectedEvent);
            service.MessageService.HeartBeatFromServer += new EventHandler(MessageService_HeartBeatFromServer);
            ServiceList.Add(service);

        }

        static void MessageService_HeartBeatFromServer(object sender, EventArgs e)
        {
            if (HeartBeatMessage != null) HeartBeatMessage(sender, e);
        }

        static void MessageService_ServerDisconnectedEvent(object sender, EventArgs e)
        {
            if (Disconnected != null) Disconnected(sender, e);
        }

        static void messageDelivered(object sender, Message e)
        {
            if (MessageDelivered != null) MessageDelivered(sender, e);
        }
        public static SAOServiceStructre<ISAOService> GetService(string name)
        {
            return ServiceList.FirstOrDefault
                (s => string.Equals(s.ServiceName, name, StringComparison.InvariantCultureIgnoreCase));
        }
        public static void RemoveService(string name)
        {
            SAOServiceStructre<ISAOService> service = GetService(name);
            if (service != null)
            {
                service.CloseService();
            }
        }
        public static SAOServiceStructre<ISAOService>[] GetServiceList()
        {
            return ServiceList.ToArray();
        }
    }
}
